package tracking.dao;
/////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright(C)  2013 NEC Corporation. All Right Reserved
//
/////////////////////////////////////////////////////////////////////////////////////////////////

/* ==========================================================================
 * Project Name: FELVServer
 * Package Features: dao
 * Class Features: Provided common functions for connect with DB.
 * File name: DBConnection.java
 * Summary: open connection with db
 * Note:
 * History: New
 * ========================================================================== */

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class DBConnection {
	private static final String DB_CONFIG = "/config.properties"; 
	private static final String DB_DRIVER = "connectdriver";
	private static final String DB_HOST = "host";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";
	private static final String TAG = "DBConnection";
	private static Connection conn = null;
	private static DBConnection instant = null; 
	
	/**
	 * Constructor
	 * @throws Exception 
	 */
	public  DBConnection(){
		
		String dbDriver ;
		String dbHost;
		String dbUser;
		String dbPassword;
		InputStream is = null;
		try {
			is = DBConnection.class.getClassLoader().getResourceAsStream(DB_CONFIG);
			Properties properties = new Properties();
			properties.load(is);
			
			//get value
			dbDriver = properties.getProperty(DB_DRIVER);
			dbHost = properties.getProperty(DB_HOST);
			dbUser = properties.getProperty(DB_USER);
			dbPassword = properties.getProperty(DB_PASSWORD);
			
//			dbDriver = "com.mysql.jdbc.Driver";
//			dbHost = "jdbc:mysql://localhost:3306/lte_data_usage_tracking";
//			dbUser = "root";
//			dbPassword = "123456";
			Class.forName(dbDriver).newInstance();
			conn = DriverManager.getConnection(dbHost, dbUser, dbPassword);
		} catch (Exception sqlEx) {
			System.out.println("log:" + "error Open Connection DAO>>>>>>>>>>" + sqlEx.toString());
			sqlEx.printStackTrace();
			conn = null;
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch (IOException ioEx) {
					ioEx.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * Get instant of DBConnection
	 * 
	 * @return DBConnection instant of DBConnection
	 * @throws Exception 
	 */
	public static DBConnection getInstant() throws Exception{
		if(instant == null){
			try {
				return  new DBConnection();
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
			
		} else {
			return instant;
		}
	}
	
	/**
	 * Get connection
	 * 
	 * @return Connection
	 */
	public Connection getConnection(){
		return conn;
	}

	
}
